# coding = utf-8
import os
import time

from project import settings
from django.db.models import Q

from rest_framework import status, filters
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from building.models import Project, BidType, Category, Document, Archive, DocType, Deposit, BidBusiness, \
    ProjectFinance, FundsDetail, BidDocument, BidInspector
from users.api.utils import get_user_by_request

from .serializers import ProjectSerializer, BidTypeSerializer, CategorySerializer, ArchiveSerializer, \
    DocumentSerializer, DocTypeSerializer, DepositSerializer, BidBusinessSerializer, ProjectListSerializer, \
    ProjectFinanceSerializer, FundsDetailSerializer, BidDocumentSerializer, BidInspectorSerializer, \
    ProjectSearchSerializer


class BidTypeViewSet(ModelViewSet):
    """标书类型"""
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = BidType.objects.all()
    serializer_class = BidTypeSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset


class CategoryViewSet(ModelViewSet):
    """工程类别"""
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset


class DocTypeViewSet(ModelViewSet):
    """资料类型"""
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = DocType.objects.all()
    serializer_class = DocTypeSerializer


class ProjectViewSet(ModelViewSet):
    """工程登记表"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['accept_date', 'open_time']

    def get_queryset(self):
        queryset = super().get_queryset()
        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        name = self.request.query_params.get("name", None)
        costs = self.request.query_params.get("costs", None)
        operator = self.request.query_params.get("operator", None)
        category = self.request.query_params.get("category", None)
        bid_type = self.request.query_params.get("bid_type", None)
        is_win = self.request.query_params.getlist("is_win[]", None)
        open_time = self.request.query_params.getlist("open_time[]")
        finish = self.request.query_params.get("finish", None)
        architect = self.request.query_params.get("architect", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        if architect:
            queryset = queryset.filter(architect__contains=architect)

        if category:
            queryset = queryset.filter(category_id=int(category))

        if bid_type:
            queryset = queryset.filter(bid_type_id=int(bid_type))

        if is_win:
            queryset = queryset.filter(is_win__in=is_win)

        if finish:
            queryset = queryset.filter(finish=int(finish))

        if open_time and len(open_time) == 2:
            queryset = queryset.filter(open_time__date__range=(open_time[0], open_time[1]))

        if operator and costs:
            if operator == "1":
                queryset = queryset.filter(costs__gt=int(costs))
            elif operator == "0":
                queryset = queryset.filter(costs__lt=int(costs))

        return queryset

    def paginate_queryset(self, queryset):
        export = self.request.query_params.get("export", None)
        if export == "1":
            self.pagination_class = None

        return super().paginate_queryset(queryset)

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class ProjectListAPIView(ListAPIView):
    """工程列表"""
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = Project.objects.all()
    serializer_class = ProjectListSerializer


class ProjectSearchAPIView(ListAPIView):
    """工程搜索列表"""
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = Project.objects.all()
    serializer_class = ProjectSearchSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset


class ArchiveViewSet(ModelViewSet):
    """工程档案"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = Archive.objects.all()
    serializer_class = ArchiveSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        name = self.request.query_params.get("name", None)
        search_date = self.request.query_params.getlist("search_date[]")
        costs = self.request.query_params.get("costs", None)          # 工程档案
        category = self.request.query_params.get("category", None)
        architect = self.request.query_params.get("architect", None)
        is_bid = self.request.query_params.get("is_bid", None)
        operator = self.request.query_params.get("operator", None)

        if category:
            queryset = queryset.filter(project__category_id=int(category))

        if architect:
            queryset = queryset.filter(Q(project__architect__contains=architect))

        if name:
            queryset = queryset.filter(Q(project__name__contains=name) | Q(code__contains=name))

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(archive_date__range=(search_date[0], search_date[1]))

        if is_bid:
            queryset = queryset.filter(is_bid=int(is_bid))

        if operator and costs:
            if operator == "1":
                queryset = queryset.filter(costs__gt=int(costs))
            elif operator == "0":
                queryset = queryset.filter(costs__lt=int(costs))

        return queryset


class DocumentViewSet(ModelViewSet):
    """档案资料"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = Document.objects.all()
    serializer_class = DocumentSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        archive_id = self.request.query_params.get("archive_id")

        if archive_id:
            queryset = queryset.filter(archive_id=archive_id)

        return queryset


class DocumentListAPIView(ListAPIView):
    """档案资料"""
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = Document.objects.all()
    serializer_class = DocumentSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        archive_id = self.request.query_params.get("archive_id")

        if archive_id:
            queryset = queryset.filter(archive_id=archive_id)

        return queryset


class DocumentUploadAPIView(APIView):
    # authentication_classes = ()
    def post(self, request, *args, **kwargs):
        # 接收文件
        file = request.FILES.get('content', None)
        archive_id = request.data.get("archive_id", None)
        doc_type = request.data.get("doc_type_id", None)

        print(file, archive_id, doc_type)
        if file and archive_id:
            upload_path = Document.content.field.upload_to
            dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
            if not os.path.exists(dirs):
                os.makedirs(dirs)

            file_info = file.name.rsplit(".", 1)
            old_file_name = file_info[0]
            file_suffix = file_info[1]
            file_name = '{0}_{1}.{2}'.format(old_file_name, int(time.time()), file_suffix)
            file_path = os.path.join(dirs, file_name)

            with open(file_path, 'wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)

            file_url = '{0}{1}'.format(upload_path, file_name)
            data = {
                'archive_id': archive_id,
                'doc_type_id': doc_type,
                'name': file.name,
                'content': file_url,
            }

            obj = Document.objects.create(**data)
            dict_obj = {
                "id":   obj.id,
                "doc_type": obj.doc_type_id,
                "doc_type_name": obj.doc_type.name,
                "name": obj.name,
                "archive_id": obj.archive_id,
                "content": "{}://{}{}".format(request.scheme, request.get_host(), obj.content.url),
            }

            msg = {
                "status_code": status.HTTP_200_OK,
                "file": dict_obj,
            }
            return Response(msg)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "上传失败!"})


class DepositViewSet(ModelViewSet):
    """保证金"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = Deposit.objects.all()
    serializer_class = DepositSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        name = self.request.query_params.get("name", None)
        search_date = self.request.query_params.getlist("search_date[]")

        if name:
            queryset = queryset.filter(project__name__contains=name)

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(Q(pay_date__range=(search_date[0], search_date[1])) | Q(refund_date__range=(search_date[0], search_date[1])))

        return queryset


class BidBusinessViewSet(ModelViewSet):
    """投标业务明细"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = BidBusiness.objects.all()
    serializer_class = BidBusinessSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        name = self.request.query_params.get("name", None)
        search_date = self.request.query_params.getlist("search_date[]")

        if name:
            queryset = queryset.filter(project__contains=name)

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(bid_date__range=(search_date[0], search_date[1]))

        return queryset


class BidDocumentViewSet(ModelViewSet):
    """投标资料"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = BidDocument.objects.all()
    serializer_class = BidDocumentSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        bid_id = self.request.query_params.get("bid_id")

        if bid_id:
            queryset = queryset.filter(bid_id=bid_id)

        return queryset


class BidInspectorViewSet(ModelViewSet):
    """检查人员"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = BidInspector.objects.all()
    serializer_class = BidInspectorSerializer


class BidDocumentUploadAPIView(APIView):
    # authentication_classes = ()
    def post(self, request, *args, **kwargs):
        # 接收文件
        file = request.FILES.get('content', None)
        bid_id = request.data.get("bid_id", None)
        doc_type = request.data.get("doc_type", None)

        print(file, bid_id, doc_type)
        if file and bid_id:
            upload_path = BidDocument.content.field.upload_to
            dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
            if not os.path.exists(dirs):
                os.makedirs(dirs)

            file_info = file.name.rsplit(".", 1)
            old_file_name = file_info[0]
            file_suffix = file_info[1]
            file_name = '{0}_{1}.{2}'.format(old_file_name, int(time.time()), file_suffix)
            file_path = os.path.join(dirs, file_name)

            with open(file_path, 'wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)

            file_url = '{0}{1}'.format(upload_path, file_name)
            data = {
                'bid_id': bid_id,
                'doc_type': doc_type,
                'name': file.name,
                'content': file_url,
            }

            doc = BidDocument(**data)
            doc.save()
            obj = BidDocument.objects.filter(id=doc.id).first()
            dict_obj = {
                "id":   obj.id,
                "doc_type": obj.doc_type,
                "doc_type_name": obj.get_doc_type_display(),
                "name": obj.name,
                "bid_id": obj.bid_id,
                "content": "{}://{}{}".format(request.scheme, request.get_host(), obj.content.url),
            }

            msg = {
                "status_code": status.HTTP_200_OK,
                "file": dict_obj,
            }
            return Response(msg)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "上传失败!"})


class ProjectFinanceViewSet(ModelViewSet):
    """工程项目财务综合统计"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = ProjectFinance.objects.all()
    serializer_class = ProjectFinanceSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        name = self.request.query_params.get("name", None)
        search_date = self.request.query_params.getlist("search_date[]")

        if name:
            queryset = queryset.filter(Q(project__name__contains=name) | Q(company__contains=name))

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(add_time__date__range=(search_date[0], search_date[1]))

        return queryset


class FundsDetailViewSet(ModelViewSet):
    """工程收入支出明细"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = FundsDetail.objects.all()
    serializer_class = FundsDetailSerializer
